package com.cybertron.ironhide.spider;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class Settings {

	private final static Logger logger = Logger.getLogger(Settings.class);

	public static Boolean IS_DEBUG = false;

	public static final String OS_NAME = System.getProperty("os.name")
			.toLowerCase();

	public static final Boolean IS_WINDOWS = OS_NAME.indexOf("windows") != -1 ? true
			: false;

	public static final Boolean IS_LINUX = OS_NAME.indexOf("linux") != -1 ? true
			: false;
	public static final String SPIDER_HOME = System.getProperty("spider.home");

	public static final String SPIDER_ID = System.getProperty("spider.id");

	public static final int IMAGE_MAX_DIM = 300;

	public static final String RFC3339_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

	public static String RESOURCE_ROOT_PATH;

	public static String SOLR_SERVER;

	public static final String PROPERTIES_FILE = "ironhide.properties";

	public static final String WEB_SITE_XML_FOLDER = SPIDER_HOME
			+ File.separator + "sites";

	public static final String WEB_PLUGIN_XML_FILE = WEB_SITE_XML_FOLDER
			+ File.separator + "plugin" + File.separator + "site_plugins.xml";

	public static final String WEB_SITE_VISITED_FOLDER = "visited";

	public static final Integer DEFAULT_MAX_COUNT = 1000;

	public static final int HTTP_FETCH_RETRY = 3;

	public static final long HTTP_FETCH_TIMEOUT = 5 * 1000;

	static {
		org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
		if (logger.isDebugEnabled()) {
			logger.debug("loading properties...");
		}
		ResourceLoader loader = new DefaultResourceLoader();
		Resource resource = loader.getResource("classpath:" + PROPERTIES_FILE);
		InputStream is = null;
		Properties prop = new Properties();

		try {
			is = resource.getInputStream();
			prop.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		IS_DEBUG = Boolean.valueOf(prop.getProperty("IS_DEBUG", "false"));

		RESOURCE_ROOT_PATH = prop.getProperty("RESOURCE_ROOT_PATH");

		SOLR_SERVER = prop.getProperty("SOLR_SERVER");

		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (prop != null) {
			prop.clear();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("loaded properties...");
		}
	}

	public static String getRealPath() {
		String realPath = Settings.class.getClassLoader().getResource("/")
				.getFile();
		File file = new File(realPath);
		realPath = file.getAbsolutePath();
		try {
			realPath = URLDecoder.decode(realPath, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return realPath;
	}

}
